import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:Sayagh/Configs.dart';
import 'package:Sayagh/i18n/i18nLocale.dart';
import 'package:flutter/material.dart';


Future<List<Map<String,dynamic>>> wpPosts({String url,int categoryId}) async {
    if (url == null) url = website + "/wp-json/wp/v2/posts";
    if (categoryId != null) url = url + "?categories=$categoryId";
    HttpClient client = HttpClient();
    HttpClientRequest req = await client.getUrl(Uri.parse(url));
    HttpClientResponse res = await req.close();
    StringBuffer content = new StringBuffer();
    Completer completer = new Completer();
    Stream<String> transformer =  res.transform(Utf8Decoder());
    transformer.listen((onData)=>content.write(onData)).onDone(()=>completer.complete(content));
    String postsStr = (await completer.future).toString();
    List<Map<String,dynamic>> returnData = [];
    var b = json.decode(postsStr);
    b.forEach((i)=>returnData.add(i));
    return(returnData);
}

class WpPosts extends StatefulWidget {
  final int _catId;
  final String _url;
  WpPosts(this._url,this._catId);
  @override
  State<StatefulWidget> createState() => _WpPosts();
}
class _WpPosts extends State<WpPosts> {
  @override
  Widget build(BuildContext context) {
    Future<List<Map>> _posts = wpPosts(
        url: widget._url,
        categoryId: widget._catId);
    return Scaffold(appBar: AppBar(title: asnafHeader,),
    body: FutureBuilder(
      future: _posts,
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        if(snapshot.data == null ){
          return Card(
              child: Text(i18nLocale[ourLocale]['reciving']),
            ); 
        }
        return ListView.builder(
          itemCount: snapshot.data.length,
          itemBuilder: (BuildContext context, int index) {
        return Card(child:InkWell(
        child: Text(
          snapshot.data[index]['title']['rendered'],
          textDirection: TextDirection.rtl,
          textAlign: TextAlign.center,
          
          ),
        onTap: ()=>{launchURL(snapshot.data[index]['link'])},
        ));
        },

        );
      },),
    );
  }
}